package com.uwo.house.controller;

import com.alibaba.fastjson.JSONObject;
import com.uwo.house.beans.Member;
import com.uwo.house.beans.User;
import com.uwo.house.service.serviceImpl.UserService;
import com.uwo.house.util.HttpUtil;
import com.uwo.house.util.ThirdPartyLoginHelper;
import com.uwo.house.util.ThirdPartyResources;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 第三方登录控制类f
 */
@Controller
@RequestMapping("/thirdPartyLogin")
public class ThirdPartyLoginController {
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/sns", method = RequestMethod.GET)
	public void thirdLogin(HttpServletRequest request, HttpServletResponse response, @RequestParam("type") String type) {
		String url = getRedirectUrl(request, type);
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@RequestMapping("/callback/wx")
	public String wxCallback(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String host = request.getHeader("host");
		String unionid = "";
		try {
			String code = request.getParameter("code");
			if (StringUtils.isNotBlank(code)) {// 如果不为空
				// 获取token和openid
				Map<String, String> map = ThirdPartyLoginHelper.getWxTokenAndOpenid(code, host);
				String openId = map.get("openId");
				if (StringUtils.isNotBlank(openId)) {// 如果openID存在
					Member member = new Member();
					String url = ThirdPartyResources.GETUserInfoURLWX;
					url = url + "?access_token=" + map.get("access_token") + "&openid=" + openId;
					String res = HttpUtil.httpClientPost(url);
					JSONObject json = JSONObject.parseObject(res);
					if (json.getString("errcode") == null) {
						member.setNickname(json.getString("nickname"));
						String img = json.getString("headimgurl");
						if (img != null && !"".equals(img)) {
							member.setFace(img);
						}
						String sex = json.getString("sex");
						if ("1".equals(sex)) {
							member.setSex(1);
						} else if ("2".equals(sex)) {
							member.setSex(2);
						}

						// 根据unionid查找用户，如果没找到后台自动注册username为unionid的用户
						unionid = json.getString("unionid");
						User user = userService.selectByUnionid(unionid);
						if(user==null) {
							//用户类型3:微信
							userService.autoRegister(unionid, "3", member);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 跳转登录
		return "redirect:http://www.lanhangf.com/user/login.html?username=" + unionid + "&password=123456&provider=wx";
	}

	@RequestMapping("/callback/wx_mobile")
	public String wxMCallback(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String host = request.getHeader("host");
		String unionid = "";
		try {
			String code = request.getParameter("code");
			if (StringUtils.isNotBlank(code)) {// 如果不为空
				// 获取token和openid
				Map<String, String> map = ThirdPartyLoginHelper.getWxTokenAndOpenid(code, host);
				String openId = map.get("openId");
				if (StringUtils.isNotBlank(openId)) {// 如果openID存在
					Member member = new Member();
					String url = ThirdPartyResources.GETUserInfoURLWX;
					url = url + "?access_token=" + map.get("access_token") + "&openid=" + openId;
					String res = HttpUtil.httpClientPost(url);
					JSONObject json = JSONObject.parseObject(res);
					if (json.getString("errcode") == null) {
						member.setNickname(json.getString("nickname"));
						String img = json.getString("headimgurl");
						if (img != null && !"".equals(img)) {
							member.setFace(img);
						}
						String sex = json.getString("sex");
						if ("1".equals(sex)) {
							member.setSex(1);
						} else if ("2".equals(sex)) {
							member.setSex(2);
						}

						// 根据unionid查找用户，如果没找到后台自动注册username为unionid的用户
						unionid = json.getString("unionid");
						User user = userService.selectByUnionid(unionid);
						if(user==null) {
							//用户类型3:微信
							userService.autoRegister(unionid, "3", member);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 跳转登录
		return "redirect:http://www.lanhangf.com/lhM/login.html?username=" + unionid + "&password=123456&provider=wx";
	}

	@RequestMapping("/callback/qq")
	public String qqCallback(HttpServletRequest request, ModelMap modelMap) {
		String host = request.getHeader("host");
		String unionid = "";
		try {
			String code = request.getParameter("code");
			if (StringUtils.isNotBlank(code)) {// 如果不为空
				// 获取token和openid
				Map<String, String> map = ThirdPartyLoginHelper.getQQTokenAndOpenid(code, host);
				String openId = map.get("openId");
				if (StringUtils.isNotBlank(openId)) {// 如果openID存在
					Member member = new Member();
					String url = ThirdPartyResources.GETUserInfoURLQQ;
					url = url + "?access_token=" + map.get("access_token") + "&openid=" + openId;
					String res = HttpUtil.httpClientPost(url);
					JSONObject json = JSONObject.parseObject(res);
					if (json.getString("errcode") == null) {
						member.setNickname(json.getString("nickname"));
						String img = json.getString("headimgurl");
						if (img != null && !"".equals(img)) {
							member.setFace(img);
						}
						String sex = json.getString("sex");
						if ("1".equals(sex)) {
							member.setSex(1);
						} else if ("2".equals(sex)) {
							member.setSex(2);
						}

						// 根据unionid查找用户，如果没找到后台自动注册username为unionid的用户
						unionid = json.getString("unionid");
						User user = userService.selectByUnionid(unionid);
						if(user==null) {
							//用户类型2:微信
							userService.autoRegister(unionid, "2", member);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 跳转登录
		return "redirect:http://"+host+request.getServletContext().getContextPath()+"/login?username=" + unionid + "&password=123456"+ "&provider=qq";
	}

	private String getRedirectUrl(HttpServletRequest request, String type) {
		String url = "";
		//String host = request.getHeader("host");
		String host = "www.lanhangf.com";
		if ("wx".equals(type)) {
            url = ThirdPartyResources.AuthorizeURLWX + "?appid=" + ThirdPartyResources.AppIdWX + "&redirect_uri=http://" + host
                    + request.getServletContext().getContextPath() + ThirdPartyResources.RedirectUrlWX + "&response_type=code&scope=" + ThirdPartyResources.ScopeWX + "&state=lhgf#wechat_redirect";
        }else if ("qq".equals(type)) {
            url = ThirdPartyResources.AuthorizeURLQQ + "?client_id=" + ThirdPartyResources.AppIdQQ + "&response_type=code&scope="
                    + request.getServletContext().getContextPath() + ThirdPartyResources.ScopeQQ + "&redirect_uri=http://" + host + ThirdPartyResources.RedirectUrlQQ;
        }else if ("wx_mobile".equals(type)) {
			url = ThirdPartyResources.AuthorizeURLWXM + "?appid=" + ThirdPartyResources.AppIdWX + "&redirect_uri=http://" + host
					+ request.getServletContext().getContextPath() + ThirdPartyResources.RedirectUrlWXM + "&response_type=code&scope=" + ThirdPartyResources.ScopeWX + "&state=lhgf#wechat_redirect";
		}

		return url;
	}
}
